from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *
import sys
import os
import datetime
os.chdir(os.path.dirname(__file__))

class TaskManagerApp(QMainWindow):
    """
    任务管理应用 - 基于QListWidget
    功能包括：
    - 待办事项列表（支持勾选完成）
    - 购物清单管理
    - 每日计划安排
    - 支持增删改查和状态标记
    """
    
    def __init__(self, parent=None):
        super(TaskManagerApp, self).__init__(parent)
        self.setWindowTitle("任务管理应用")
        self.setGeometry(100, 100, 800, 600)
        
        # 初始化数据
        self.tasks = []  # 存储所有任务
        self.current_filter = "all"  # 当前过滤状态：all, active, completed
        
        self.init_ui()
        self.load_sample_data()
        
    def init_ui(self):
        """初始化用户界面"""
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 顶部工具栏
        toolbar_layout = QHBoxLayout()
        
        # 任务类型选择
        self.task_type_combo = QComboBox()
        self.task_type_combo.addItems(["待办事项", "购物清单", "每日计划"])
        self.task_type_combo.currentTextChanged.connect(self.on_task_type_changed)
        toolbar_layout.addWidget(QLabel("任务类型:"))
        toolbar_layout.addWidget(self.task_type_combo)
        
        # 过滤选项
        self.filter_combo = QComboBox()
        self.filter_combo.addItems(["全部", "未完成", "已完成"])
        self.filter_combo.currentTextChanged.connect(self.on_filter_changed)
        toolbar_layout.addWidget(QLabel("过滤:"))
        toolbar_layout.addWidget(self.filter_combo)
        
        toolbar_layout.addStretch()
        
        # 添加按钮
        self.add_button = QPushButton("添加任务")
        self.add_button.clicked.connect(self.on_add_task)
        toolbar_layout.addWidget(self.add_button)
        
        main_layout.addLayout(toolbar_layout)
        
        # 任务列表
        self.task_list = QListWidget()
        self.task_list.setSelectionMode(QAbstractItemView.SingleSelection)
        self.task_list.itemChanged.connect(self.on_item_changed)
        self.task_list.itemDoubleClicked.connect(self.on_item_double_clicked)
        main_layout.addWidget(self.task_list)
        
        # 底部状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        self.update_status_bar()
        
        # 创建上下文菜单
        self.create_context_menu()
        
    def create_context_menu(self):
        """创建上下文菜单"""
        self.context_menu = QMenu(self)
        
        # 编辑操作
        edit_action = QAction("编辑", self)
        edit_action.triggered.connect(self.on_edit_task)
        self.context_menu.addAction(edit_action)
        
        # 删除操作
        delete_action = QAction("删除", self)
        delete_action.triggered.connect(self.on_delete_task)
        self.context_menu.addAction(delete_action)
        
        # 标记完成/未完成
        toggle_action = QAction("切换状态", self)
        toggle_action.triggered.connect(self.on_toggle_status)
        self.context_menu.addAction(toggle_action)
        
        self.context_menu.addSeparator()
        
        # 清除已完成
        clear_action = QAction("清除已完成任务", self)
        clear_action.triggered.connect(self.on_clear_completed)
        self.context_menu.addAction(clear_action)
        
        # 设置上下文菜单策略
        self.task_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.task_list.customContextMenuRequested.connect(self.show_context_menu)
        
    def show_context_menu(self, position):
        """显示上下文菜单"""
        item = self.task_list.itemAt(position)
        if item:
            self.context_menu.exec(self.task_list.mapToGlobal(position))
            
    def load_sample_data(self):
        """加载示例数据"""
        sample_tasks = [
            {"type": "待办事项", "text": "完成项目报告", "completed": False, "priority": "高", "due_date": "2024-01-15"},
            {"type": "待办事项", "text": "准备会议材料", "completed": True, "priority": "中", "due_date": "2024-01-10"},
            {"type": "购物清单", "text": "牛奶", "completed": False, "quantity": "2盒", "category": "食品"},
            {"type": "购物清单", "text": "鸡蛋", "completed": True, "quantity": "1打", "category": "食品"},
            {"type": "每日计划", "text": "晨跑30分钟", "completed": False, "time": "07:00", "repeat": "每天"},
            {"type": "每日计划", "text": "阅读技术文档", "completed": False, "time": "20:00", "repeat": "工作日"}
        ]
        
        for task in sample_tasks:
            self.tasks.append(task)
        
        self.refresh_task_list()
        
    def refresh_task_list(self):
        """刷新任务列表显示"""
        self.task_list.clear()
        
        current_type = self.task_type_combo.currentText()
        
        for task in self.tasks:
            # 按类型过滤
            if task["type"] != current_type:
                continue
                
            # 按状态过滤
            if self.current_filter == "active" and task["completed"]:
                continue
            if self.current_filter == "completed" and not task["completed"]:
                continue
                
            # 创建列表项
            item = QListWidgetItem(self.format_task_text(task))
            item.setData(Qt.UserRole, task)
            
            # 设置复选框
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Checked if task["completed"] else Qt.Unchecked)
            
            # 设置样式
            if task["completed"]:
                font = item.font()
                font.setStrikeOut(True)
                item.setFont(font)
                item.setForeground(QBrush(QColor(128, 128, 128)))
            else:
                # 根据优先级设置颜色
                if task.get("priority") == "高":
                    item.setForeground(QBrush(QColor(255, 0, 0)))
                elif task.get("priority") == "中":
                    item.setForeground(QBrush(QColor(255, 165, 0)))
            
            self.task_list.addItem(item)
            
        self.update_status_bar()
        
    def format_task_text(self, task):
        """格式化任务文本显示"""
        text = task["text"]
        
        if task["type"] == "待办事项":
            if "due_date" in task:
                text += f" (截止: {task['due_date']})"
            if "priority" in task:
                text += f" [{task['priority']}优先级]"
                
        elif task["type"] == "购物清单":
            if "quantity" in task:
                text += f" - {task['quantity']}"
            if "category" in task:
                text += f" ({task['category']})"
                
        elif task["type"] == "每日计划":
            if "time" in task:
                text += f" @ {task['time']}"
            if "repeat" in task:
                text += f" ({task['repeat']})"
                
        return text
        
    def update_status_bar(self):
        """更新状态栏信息"""
        total = len([t for t in self.tasks if t["type"] == self.task_type_combo.currentText()])
        completed = len([t for t in self.tasks if t["type"] == self.task_type_combo.currentText() and t["completed"]])
        
        self.status_bar.showMessage(f"总计: {total} | 已完成: {completed} | 未完成: {total - completed}")
        
    def on_task_type_changed(self, task_type):
        """任务类型改变时的处理"""
        self.refresh_task_list()
        
    def on_filter_changed(self, filter_text):
        """过滤条件改变时的处理"""
        if filter_text == "全部":
            self.current_filter = "all"
        elif filter_text == "未完成":
            self.current_filter = "active"
        elif filter_text == "已完成":
            self.current_filter = "completed"
            
        self.refresh_task_list()
        
    def on_item_changed(self, item):
        """列表项改变时的处理（复选框状态改变）"""
        task = item.data(Qt.UserRole)
        if task:
            task["completed"] = (item.checkState() == Qt.Checked)
            
            # 更新样式
            font = item.font()
            font.setStrikeOut(task["completed"])
            item.setFont(font)
            
            if task["completed"]:
                item.setForeground(QBrush(QColor(128, 128, 128)))
            else:
                # 恢复原始颜色
                if task.get("priority") == "高":
                    item.setForeground(QBrush(QColor(255, 0, 0)))
                elif task.get("priority") == "中":
                    item.setForeground(QBrush(QColor(255, 165, 0)))
                else:
                    item.setForeground(QBrush(QColor(0, 0, 0)))
            
            self.update_status_bar()
            
    def on_item_double_clicked(self, item):
        """双击列表项进行编辑"""
        self.on_edit_task()
        
    def on_add_task(self):
        """添加新任务"""
        dialog = TaskDialog(self)
        if dialog.exec() == QDialog.Accepted:
            new_task = dialog.get_task_data()
            new_task["type"] = self.task_type_combo.currentText()
            self.tasks.append(new_task)
            self.refresh_task_list()
            
    def on_edit_task(self):
        """编辑选中的任务"""
        current_item = self.task_list.currentItem()
        if not current_item:
            QMessageBox.warning(self, "警告", "请先选择一个任务进行编辑")
            return
            
        task_data = current_item.data(Qt.UserRole)
        dialog = TaskDialog(self, task_data)
        
        if dialog.exec() == QDialog.Accepted:
            # 更新任务数据
            updated_data = dialog.get_task_data()
            task_data.update(updated_data)
            
            # 更新显示
            current_item.setText(self.format_task_text(task_data))
            self.refresh_task_list()
            
    def on_delete_task(self):
        """删除选中的任务"""
        current_item = self.task_list.currentItem()
        if not current_item:
            QMessageBox.warning(self, "警告", "请先选择一个任务进行删除")
            return
            
        task_data = current_item.data(Qt.UserRole)
        
        reply = QMessageBox.question(self, "确认删除", 
                                   f"确定要删除任务 '{task_data['text']}' 吗？",
                                   QMessageBox.Yes | QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            self.tasks.remove(task_data)
            self.refresh_task_list()
            
    def on_toggle_status(self):
        """切换任务状态"""
        current_item = self.task_list.currentItem()
        if not current_item:
            QMessageBox.warning(self, "警告", "请先选择一个任务")
            return
            
        task_data = current_item.data(Qt.UserRole)
        task_data["completed"] = not task_data["completed"]
        
        # 更新复选框状态
        current_item.setCheckState(Qt.Checked if task_data["completed"] else Qt.Unchecked)
        self.on_item_changed(current_item)
        
    def on_clear_completed(self):
        """清除所有已完成的任务"""
        reply = QMessageBox.question(self, "确认清除", 
                                   "确定要清除所有已完成的任务吗？",
                                   QMessageBox.Yes | QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            self.tasks = [task for task in self.tasks if not task["completed"]]
            self.refresh_task_list()


class TaskDialog(QDialog):
    """任务编辑对话框"""
    
    def __init__(self, parent=None, task_data=None):
        super(TaskDialog, self).__init__(parent)
        self.task_data = task_data or {}
        self.setWindowTitle("编辑任务" if task_data else "添加任务")
        self.init_ui()
        
    def init_ui(self):
        """初始化对话框界面"""
        layout = QVBoxLayout(self)
        
        # 任务描述
        layout.addWidget(QLabel("任务描述:"))
        self.text_edit = QLineEdit(self.task_data.get("text", ""))
        layout.addWidget(self.text_edit)
        
        # 根据任务类型显示不同的字段
        task_type = self.parent().task_type_combo.currentText() if self.parent() else "待办事项"
        
        if task_type == "待办事项":
            # 优先级
            layout.addWidget(QLabel("优先级:"))
            self.priority_combo = QComboBox()
            self.priority_combo.addItems(["低", "中", "高"])
            self.priority_combo.setCurrentText(self.task_data.get("priority", "中"))
            layout.addWidget(self.priority_combo)
            
            # 截止日期
            layout.addWidget(QLabel("截止日期 (YYYY-MM-DD):"))
            self.due_date_edit = QLineEdit(self.task_data.get("due_date", ""))
            layout.addWidget(self.due_date_edit)
            
        elif task_type == "购物清单":
            # 数量
            layout.addWidget(QLabel("数量:"))
            self.quantity_edit = QLineEdit(self.task_data.get("quantity", ""))
            layout.addWidget(self.quantity_edit)
            
            # 分类
            layout.addWidget(QLabel("分类:"))
            self.category_combo = QComboBox()
            self.category_combo.addItems(["食品", "日用品", "服装", "电子产品", "其他"])
            self.category_combo.setCurrentText(self.task_data.get("category", "其他"))
            layout.addWidget(self.category_combo)
            
        elif task_type == "每日计划":
            # 时间
            layout.addWidget(QLabel("时间 (HH:MM):"))
            self.time_edit = QLineEdit(self.task_data.get("time", ""))
            layout.addWidget(self.time_edit)
            
            # 重复
            layout.addWidget(QLabel("重复:"))
            self.repeat_combo = QComboBox()
            self.repeat_combo.addItems(["不重复", "每天", "工作日", "每周", "每月"])
            self.repeat_combo.setCurrentText(self.task_data.get("repeat", "不重复"))
            layout.addWidget(self.repeat_combo)
        
        # 按钮
        button_layout = QHBoxLayout()
        ok_button = QPushButton("确定")
        ok_button.clicked.connect(self.accept)
        cancel_button = QPushButton("取消")
        cancel_button.clicked.connect(self.reject)
        
        button_layout.addWidget(ok_button)
        button_layout.addWidget(cancel_button)
        layout.addLayout(button_layout)
        
    def get_task_data(self):
        """获取任务数据"""
        task_type = self.parent().task_type_combo.currentText() if self.parent() else "待办事项"
        
        data = {
            "text": self.text_edit.text(),
            "completed": self.task_data.get("completed", False)
        }
        
        if task_type == "待办事项":
            data.update({
                "priority": self.priority_combo.currentText(),
                "due_date": self.due_date_edit.text()
            })
        elif task_type == "购物清单":
            data.update({
                "quantity": self.quantity_edit.text(),
                "category": self.category_combo.currentText()
            })
        elif task_type == "每日计划":
            data.update({
                "time": self.time_edit.text(),
                "repeat": self.repeat_combo.currentText()
            })
            
        return data


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = TaskManagerApp()
    window.show()
    sys.exit(app.exec())